import axios from '@/services/axios'
import mockConfig from '@/mock'
import dayjs from 'dayjs'

// 根据配置生成axios请求，并mock
export const generateServices = (config = []) => config.reduce((pre, { name, mock = false, axiosConfig }) => {
	if (name && axiosConfig) {
		const needMock = process.env.VUE_APP_NEED_MOCK
		if ((needMock === '1' || !!mock) && !!mockConfig[name]) {
			pre[name] = (payload) => new Promise((resolve, reject) => {
				setTimeout(() => {
					resolve(mockConfig[name](payload))
				}, 800)
			})
			// TODO: detail mock
		} else {
			pre[name] = (payload) => axios({
				...axiosConfig,
				...payload,
			})
		}
	}
	return pre
}, {})

export const getDuration = (start, end = dayjs()) => {
	try {
		const duration = Math.abs(dayjs(start).valueOf() - dayjs(end).valueOf()) / 1000
		if (duration <= 60) {
			return `${parseInt(duration)}秒前`
		} else if (duration > 60 && duration <= 3600) {
			return `${parseInt(duration / 60)}分钟前`
		} else if (duration > 3600 && duration <= 24 * 3600) {
			return `${parseInt(duration / 3600)}小时前`
		} else {
			return `${parseInt(duration / (3600 * 24))}天前`
		}
	} catch (error) {
		console.log(error)
		throw new Error('请传入正确格式')
	}
}
/**
 * 简单防抖函数,项目体积考虑就不使用lodash库了
*/
export const debounce = (fn, delay) => {
	let timer = null
	return function () {
		clearTimeout(timer)
		timer = setTimeout(() => {
			fn.apply(this, arguments)
		}, delay)
	}
}

export const timeFormat = (val) => {
	return dayjs(val).format('YYYY-MM-DD')
}
